//
//  AppDelegate.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/2.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "LoginViewController.h"
#import "BaseNavigationController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <GoogleSignIn/GIDSignIn.h>
#import <GoogleSignIn/GIDConfiguration.h>
#import "CycLanguage.h"
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

#import "Cycling-Swift.h"
#import "HealthDataRequest.h"

#import  <UserNotifications/UserNotifications.h>
#import "APNS.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@property (nonatomic, strong) BaseTabBarController *tabbarRootVC;

@property (nonatomic) UIBackgroundTaskIdentifier taskId;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    
    [APNS regLocalAPNs];
    [APNS regRemoteAPNs:self];
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
        NSString *str = [NSString stringWithFormat:@"Location awake time = %@",[NSDate date]];
        [APNS pushNotifacation:str];
    }

    //初始化facebook SDK
    [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    NSString *token = [USERDEFAULTS valueForKey:@"Token"];
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
   
    [[CycLanguage sharedInstance] configLanguage];

    if (!IsStrEmpty(token)) {
        self.tabbarRootVC = [BaseTabBarController new];
        self.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:self.tabbarRootVC];
        [self.window makeKeyAndVisible];
        
        [HealthDataRequest requestHealthDateRangeWithComplete:nil];
    } else {
        self.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
        [self.window makeKeyAndVisible];
    }
    
    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  BOOL handled;

  handled = [GIDSignIn.sharedInstance handleURL:url];
  if (handled) {
    return YES;
  }
    [[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options];

  // Handle other custom URL types.

  // If not handled by this app, return NO.
  return NO;
}

+ (void)changeToCyclingTabWithRouteJson:(NSArray *)json
{
    UIViewController *rootVC = appDelegate.getKeyWindowRootViewController;
    if([rootVC isKindOfClass:[BaseTabBarController class]]) {
        [(BaseTabBarController *)rootVC changeToCyclingTabWithRouteJson:json];
    }
}

+ (void)changeToCyclingTabWithRouteJson:(NSArray *)json andLat:(CLLocationDistance)lat lng:(CLLocationDistance)lng
{
    UIViewController *rootVC = appDelegate.getKeyWindowRootViewController;
    if([rootVC isKindOfClass:[BaseTabBarController class]]) {
        [(BaseTabBarController *)rootVC changeToCyclingTabWithRouteJson:json andLat:lat lng:lng];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if(!self.shouldUseBackgroundTask) {
        return;
    }
    self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(),^{
            if( self.taskId != UIBackgroundTaskInvalid){
                self.taskId = UIBackgroundTaskInvalid;
            }
        });
    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if(self.taskId != 0) {
        [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
    }
    self.taskId = 0;
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSMutableString *deviceTokenString = [NSMutableString string];
    const char *bytes = deviceToken.bytes;
    NSInteger count = deviceToken.length;
    for (int i = 0; i < count; i++) {
        [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
    }
    
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", deviceTokenString);
    self.pushTocken =  deviceTokenString;
    
//    [[NSUserDefaults standardUserDefaults] setValue:deviceTokenString forKey:@"devicetoken"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n",userInfo);
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)) API_AVAILABLE(ios(10.0)) API_AVAILABLE(ios(10.0)){
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}


- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    NSDictionary *dict =  response.notification.request.content.userInfo;
    
//    if([response.actionIdentifier isEqualToString:@"ActionA"]){
        
        NSString *url = dict[@"adviewUrl"];
        if (url.length > 0) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
//                NSLog(@"完成跳转");
            }];
        }
            
//    }else{
//
//    }
    
    completionHandler();
}

//  iOS 10:
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
//
//    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
//
//    completionHandler();
//}
#endif

- (NSString *)pushString{
    NSLog(@"APNS ID = %@",self.pushTocken);
    return self.pushTocken;
}



@end
